package com.xujianlong.day06;

import javassist.expr.NewArray;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class Flink07_OperaterState_Broadcast {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> hadoop1029999 = env.socketTextStream("hadoop102", 9999);

        DataStreamSource<String> hadoop1028888 = env.socketTextStream("hadoop102", 8888);


        MapStateDescriptor<String, String> mapState = new MapStateDescriptor<>("map", String.class, String.class);
        BroadcastStream<String> broadcast = hadoop1029999.broadcast(mapState);

        BroadcastConnectedStream<String, String> connect = hadoop1028888.connect(broadcast);
        SingleOutputStreamOperator<String> process = connect.process(new BroadcastProcessFunction<String, String, String>() {
            @Override
            public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
                ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapState);

                String aSwitch = broadcastState.get("switch");

                if ("1".equals(aSwitch)) {
                    out.collect("执行逻辑1-----------------");
                } else if ("2".equals(aSwitch)) {
                    out.collect("执行逻辑2------------------");
                } else {
                    out.collect("执行其他逻辑");
                }
            }

            @Override
            public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
                BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapState);
                broadcastState.put("switch", value);
            }
        });
        process.print();
        env.execute();


    }
}
